package aos.voting.socket;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Queue;

import aos.voting.entity.Message;
import aos.voting.entity.ReportData;
import aos.voting.entity.Configuration;
import aos.voting.exception.AosException;
import aos.voting.log.LogUtils;

public class SocketListener implements Runnable {
	private ServerSocket serverSocket;
	private Queue<Message> messageQueue;
	private ReportData report;

	public SocketListener(int port, HashMap<Integer, SocketHandler> id2Socket,
			Configuration routeTable, Queue<Message> messageQueue,
			ReportData report) throws AosException {
		try {
			this.serverSocket = new ServerSocket(port);
		} catch (IOException e) {
			LogUtils.errorLog("server open socket failed, with port: " + port);
			LogUtils.errorLog(e.getMessage());
			throw new AosException(e.getMessage(), e);
		}
		this.messageQueue = messageQueue;
		this.report = report;
	}

	@Override
	public void run() {
		while (true) {
			Socket socket = null;
			SocketHandler socketHandler = null;
			try {
				socket = serverSocket.accept();
				socketHandler = new SocketHandler(socket, messageQueue, report);
			} catch (IOException e) {
				LogUtils.errorLog(e.getMessage());
				continue;
			}
			LogUtils.runLog("serverSocket accept, connect with "
					+ socket.getInetAddress().getHostAddress());
			new Thread(socketHandler).start();

		}
	}
}
